package com.symaster.common.geom.entity;

import com.symaster.common.geom.clipper.DefaultClipper;
import com.symaster.common.geom.clipper.Path;
import com.symaster.common.geom.clipper2.Clipper;
import com.symaster.common.geom.clipper2.core.PathD;
import com.symaster.common.geom.clipper2.core.PathsD;
import com.symaster.common.geom.clipper2.core.PointD;
import com.symaster.common.geom.clipper2.offset.EndType;
import com.symaster.common.geom.clipper2.offset.JoinType;
import com.symaster.common.geom.nest4j.data.NestPath;
import com.symaster.common.geom.nest4j.data.Segment;
import com.symaster.common.geom.nest4j.util.coor.ClipperCoor;
import com.symaster.common.geom.util.ArithUtil;
import com.symaster.common.geom.util.IDUtil;
import com.symaster.common.geom.util.PointUtil;
import com.symaster.common.geom.util.UnitUtil;
import org.opencv.core.MatOfPoint;
import org.opencv.core.MatOfPoint2f;
import org.opencv.imgproc.Imgproc;

import java.awt.geom.AffineTransform;
import java.awt.geom.PathIterator;
import java.awt.geom.Rectangle2D;
import java.io.Serializable;
import java.util.*;

/**
 * 多边形实体
 *
 * @author yinmiao
 * @version 2021-08-10 08:31
 */
public class Polygon implements Serializable, Cloneable {

    private static final long serialVersionUID = -34972314592345L;

    private int bId;
    private String id;
    private double[] xpoints, ypoints;
    private Double x, y, maxX, maxY, width, height;
    private int npoints;

    @Deprecated
    public Polygon() {
        this(null, null);
    }

    public Polygon(double[] xPoints, double[] yPoints) {
        this(xPoints, yPoints, UUID.randomUUID().toString());
    }

    public Polygon(double[] xPoints, double[] yPoints, String id) {
        this(xPoints, yPoints, id, IDUtil.getId());
    }

    public Polygon(double[] xPoints, double[] yPoints, String id, int bid) {
        npoints = 0;
        if (xPoints != null) {
            npoints = xPoints.length;
            this.xpoints = xPoints;
            this.ypoints = yPoints;
            if (yPoints == null) {
                throw new NullPointerException("yPoints Is Empty");
            }
            if (this.xpoints.length != this.ypoints.length) {
                throw new IllegalArgumentException("xPoints.length != yPoints.length");
            }
        }

        this.bId = bid;
        this.id = id;
    }

    public int getBId() {
        return bId;
    }

    public void reverse() {
        double[] doubles = new double[xpoints.length];

        for (int i1 = xpoints.length - 1, i2 = 0; i1 >= 0; i1--, i2++) {
            doubles[i2] = xpoints[i1];
        }
        System.arraycopy(doubles, 0, xpoints, 0, xpoints.length);

        for (int i1 = ypoints.length - 1, i2 = 0; i1 >= 0; i1--, i2 ++) {
            doubles[i2] = ypoints[i1];
        }
        System.arraycopy(doubles, 0, ypoints, 0, ypoints.length);
    }

    public double circumference() {
        if (isEmpty()) {
            return 0.0D;
        }
        double circumference = 0.0D;
        for (int i = 0; i < xpoints.length; i++) {
            int eInd = i + 1 < xpoints.length ? i + 1 : 0;
            circumference += PointUtil.dis(new Point(xpoints[i], ypoints[i]), new Point(xpoints[eInd], ypoints[eInd]));
        }
        return circumference;
    }

    public Polygon pxToMm(double dpi) {
        double[] xPoints = new double[npoints];
        double[] yPoints = new double[npoints];
        for (int i = 0; i < xpoints.length; i++) {
            xPoints[i] = UnitUtil.pxToMm(xpoints[i], dpi);
            yPoints[i] = UnitUtil.pxToMm(ypoints[i], dpi);
        }
        return new Polygon(xPoints, yPoints);
    }

    public Point getPoint() {
        return new Point(getX(), getY());
    }

    public Circle minEnclosingCircle() {
        org.opencv.core.Point[] points = PointUtil.polygon2OpencvPointArray(this);
        MatOfPoint2f matOfPoint2f = new MatOfPoint2f(points);

        org.opencv.core.Point center = new org.opencv.core.Point();
        float[] radius = new float[1];
        Imgproc.minEnclosingCircle(matOfPoint2f, center, radius);
        Circle circle = new Circle();
        circle.setCenter(new Point(center.x, center.y));
        circle.setRadius((double) radius[0]);
        return circle;
    }

    public RotatedRect minAreaRect() {
        org.opencv.core.Point[] points = PointUtil.polygon2OpencvPointArray(this);
        MatOfPoint2f matOfPoint2f = new MatOfPoint2f(points);

        org.opencv.core.RotatedRect rotatedRect = Imgproc.minAreaRect(matOfPoint2f);
        RotatedRect rotatedRect1 = new RotatedRect();
        rotatedRect1.setCenter(new Point(rotatedRect.center.x, rotatedRect.center.y));
        rotatedRect1.setSize(new Size(rotatedRect.size.width, rotatedRect.size.height));
        rotatedRect1.setAngle(rotatedRect.angle);
        return rotatedRect1;
    }

    public List<LineSegment> toLineSegment() {
        List<Point> pointList = toPointList();
        List<LineSegment> lines = new ArrayList<>();

        int pointSize = pointList.size();

        for (int i = 0; i < pointSize; i++) {

            Point end;
            if (i >= pointSize - 1) {
                end = pointList.get(0);
            } else {
                end = pointList.get(i + 1);
            }

            LineSegment lineSegment = new LineSegment(pointList.get(i), end);
            lines.add(lineSegment);
        }
        return lines;
    }

    public LineSegment lineIterator(boolean close) {
        LineSegment master = null;
        LineSegment last = null;
        for (int i = 0; i < xpoints.length; i++) {
            boolean end = !(i + 1 < xpoints.length);
            LineSegment lineSegment = new LineSegment(new Point(xpoints[i], ypoints[i]), new Point(xpoints[end ? 0 : i + 1], xpoints[end ? 0 : i + 1]));
            if (master == null) {
                master = lineSegment;
                last = lineSegment;
                continue;
            }
            last.setNext(lineSegment);
            last = lineSegment;
            if (end && close) {
                lineSegment.setNext(master);
            }
        }
        return master;
    }

    public Polygon offsetOfCopy(double offset) {
        PathD pointDS = toPathD();
        PathsD of = PathsD.of(pointDS);
        PathsD pathDS = Clipper.InflatePaths(of, offset, JoinType.Round, EndType.Polygon);
        if (pathDS.isEmpty()) {
            throw new IllegalArgumentException("等距缩放异常");
        }

        PathD pointDS1 = pathDS.get(0);
        Polygon polygon = Polygon.ofPathD(pointDS1);
        return PointUtil.approxPolyDp(polygon, 1);
    }

    public NestPath toNestPath() {
        if (isEmpty()) {
            throw new IllegalArgumentException("polygon is empty!");
        }

        NestPath nestPath = new NestPath();
        for (int i = 0; i < xpoints.length; i++) {
            nestPath.add(xpoints[i], ypoints[i]);
        }

        nestPath.bid = bId;
        return nestPath;
    }

    public Path toClipperPath() {
        throwEmpty();
        Path path = new Path();
        for (int i = 0; i < xpoints.length; i++) {
            ClipperCoor clipperCoor = com.symaster.common.geom.nest4j.util.CommonUtil.toClipperCoor(xpoints[i], ypoints[i]);
            com.symaster.common.geom.clipper.Point.LongPoint lp = new com.symaster.common.geom.clipper.Point.LongPoint(clipperCoor.getX(), clipperCoor.getY());
            path.add(lp);
        }
        return path;
    }

    public static Polygon ofNestPath(NestPath nestPath) {
        double[] xPoints = new double[nestPath.size()];
        double[] yPoints = new double[nestPath.size()];
        for (int i = 0; i < nestPath.size(); i++) {
            Segment segment = nestPath.get(i);
            xPoints[i] = segment.x;
            yPoints[i] = segment.y;
        }
        return new Polygon(xPoints, yPoints);
    }

    public PathD toPathD() {
        List<PointD> pointDS = new ArrayList<>(npoints);
        for (int i = 0; i < xpoints.length; i++) {
            pointDS.add(new PointD(xpoints[i], ypoints[i]));
        }
        return new PathD(pointDS);
    }

    public static Polygon ofPathD(PathD pathD) {
        if (pathD == null || pathD.size() == 0) {
            return null;
        }

        double[] xPoints = new double[pathD.size()];
        double[] yPoints = new double[pathD.size()];
        for (int i = 0; i < pathD.size(); i++) {
            xPoints[i] = pathD.get(i).x;
            yPoints[i] = pathD.get(i).y;
        }
        return new Polygon(xPoints, yPoints);
    }

    public double similarity(Polygon p) {
        MatOfPoint matOfPoint1 = PointUtil.polygon2MatOfPoint(this);
        MatOfPoint matOfPoint = PointUtil.polygon2MatOfPoint(p);
        return 1.0D - Imgproc.matchShapes(matOfPoint1, matOfPoint, Imgproc.CONTOURS_MATCH_I3, 0);
    }

    public double similarity2(Polygon p) {

        Point center = getCenter();
        Vector translateVector = PointUtil.getTranslateVector(p.getCenter(), center);
        Polygon clone = p.clone();
        clone.translate(translateVector);

        com.symaster.common.geom.clipper.Paths result = new com.symaster.common.geom.clipper.Paths();
        com.symaster.common.geom.clipper.Clipper defaultClipper = new DefaultClipper();
        defaultClipper.addPath(this.toClipperPath(), com.symaster.common.geom.clipper.Clipper.PolyType.SUBJECT, true);
        defaultClipper.addPath(clone.toClipperPath(), com.symaster.common.geom.clipper.Clipper.PolyType.SUBJECT, true);
        boolean execute = defaultClipper.execute(com.symaster.common.geom.clipper.Clipper.ClipType.XOR, result);
        if (!execute) {
            return 0.0D;
        }

        double sum = result.stream().mapToDouble(Path::polygonArea).sum();
        double v = (getArea() + clone.getArea()) / 2;
        double v1 = (v - sum) / v;
        return Math.max(v1, 0.0D);
    }

    public double similarity(Polygon p, double epsilon) {
        int round = (int) Math.round(360 / epsilon);

        double[] rtn = new double[round];
        LineSegment line1 = new LineSegment(new Point(getX() - 100, getY() - 100), new Point(getX() + getWidth() + 100, getY() + getHeight() + 100));
        LineSegment line2 = new LineSegment(new Point(p.getX() - 100, p.getY() - 100), new Point(p.getX() + p.getWidth() + 100, p.getY() + p.getHeight() + 100));
        for (int i = 0; i < round; i++) {
            if (i != 0) {
                line1.rotate(line1.center(), epsilon);
                line2.rotate(line2.center(), epsilon);
            }

            rtn[i] = getDim(getCrossPoint(line1), p.getCrossPoint(line2));
        }

        return Arrays.stream(rtn).sum() / round;
    }

    public double similarity(Polygon p, int epsilon) {

        double[] rtn = new double[epsilon];

        LineSegment p1YLine = new LineSegment(new Point(getX() - 100, getY() + getHeight() / epsilon / 2.0), new Point(getX() + getWidth() + 100, getY() + getHeight() / epsilon / 2.0));
        LineSegment p2YLine = new LineSegment(new Point(p.getX() - 100, p.getY() + p.getHeight() / epsilon / 2.0), new Point(p.getX() + p.getWidth() + 100, p.getY() + p.getHeight() / epsilon / 2.0));
        LineSegment p1XLine = new LineSegment(new Point(getX() + getWidth() / epsilon / 2.0, getY() - 100), new Point(getX() + getWidth() / epsilon / 2.0, getY() + getHeight() + 100));
        LineSegment p2XLine = new LineSegment(new Point(p.getX() + p.getWidth() / epsilon / 2.0, p.getY() - 100), new Point(p.getX() + p.getWidth() / epsilon / 2.0, p.getY() + p.getHeight() + 100));

        double yOffset = Math.max(this.getHeight(), p.getHeight()) / epsilon;
        double xOffset = Math.max(this.getWidth(), p.getWidth()) / epsilon;

        for (int i = 0; i < epsilon; i++) {
            if (i != 0) {
                p1YLine.translate(0.0D, yOffset);
                p2YLine.translate(0.0D, yOffset);
                p1XLine.translate(xOffset, 0.0D);
                p2XLine.translate(xOffset, 0.0D);
            }

            List<Point> p1XCrossPoint = getCrossPoint(p1XLine);
            List<Point> p1YCrossPoint = getCrossPoint(p1YLine);
            List<Point> p2XCrossPoint = p.getCrossPoint(p2XLine);
            List<Point> p2YCrossPoint = p.getCrossPoint(p2YLine);

            if (p1YCrossPoint.size() < 2) {
                rtn[i] = p2YCrossPoint.size() < 2 ? 1.0D : 0.0D;
                continue;
            }
            if (p2YCrossPoint.size() < 2) {
                rtn[i] = 0.0D;
                continue;
            }

            double xDim = getXDim(p1XCrossPoint, p2XCrossPoint, p1XLine.center(), p2XLine.center());
            double yDim = getYDim(p1YCrossPoint, p2YCrossPoint, p1YLine.center(), p2YLine.center());
            rtn[i] = (xDim + yDim) / 2.0D;
        }

        return Arrays.stream(rtn).sum() / rtn.length;
    }

    private double getYDim(List<Point> p1YCrossPoint, List<Point> p2YCrossPoint, Point line1Center, Point line2Center) {
        double[] p1 = p1YCrossPoint.stream().mapToDouble(Point::getX).toArray();
        double[] p2 = p2YCrossPoint.stream().mapToDouble(Point::getX).toArray();
        return getDim(p1, p2, line1Center.getX(), line2Center.getX());
    }

    private double getXDim(List<Point> p1XCrossPoint, List<Point> p2XCrossPoint, Point line1Center, Point line2Center) {
        double[] p1 = p1XCrossPoint.stream().mapToDouble(Point::getY).toArray();
        double[] p2 = p2XCrossPoint.stream().mapToDouble(Point::getY).toArray();
        return getDim(p1, p2, line1Center.getY(), line2Center.getY());
    }

    private double getDim(double[] p1, double[] p2, double p1Center, double p2Center) {

        double p1Max = Arrays.stream(p1).max().orElse(0.0D);
        double p1Min = Arrays.stream(p1).min().orElse(0.0D);
        double p2Max = Arrays.stream(p2).max().orElse(0.0D);
        double p2Min = Arrays.stream(p2).min().orElse(0.0D);

        // p1Center
        // p1Min + (p1Max - p1Min) / 2

        // p2Center
        // p2Min + (p2Max - p2Min) / 2

        double v1 = p1Center - p1Min + (p1Max - p1Min) / 2;
        double v2 = p2Center - p2Min + (p2Max - p2Min) / 2;

        // double v1 = Math.max(p1Center, p1Min + (p1Max - p1Min) / 2) - Math.min(p1Center, p1Min + (p1Max - p1Min) / 2);
        // double v2 = Math.max(p2Center, p2Min + (p2Max - p2Min) / 2) - Math.min(p2Center, p2Min + (p2Max - p2Min) / 2);
        double v3 = Math.max(Math.min(v1, v2), 1) / Math.max(Math.max(v1, v2), 1);
        double v4 = Math.max(Math.min(p1Max - p1Min, p2Max - p2Min), 1) / Math.max(Math.max(p1Max - p1Min, p2Max - p2Min), 1);

        return (v3 + v4) <= 0.0D ? 0.0D : (v3 + v4) / 2.0;
    }

    private double getDim(List<Point> crossPoint, List<Point> crossPoint2) {
        if (crossPoint.size() != crossPoint2.size()) {
            return 0.0D;
        }
        if (crossPoint.size() != 2) {
            return 1.0D;
        }

        LineSegment lineSegment1 = new LineSegment(crossPoint.get(0), crossPoint.get(1));
        LineSegment lineSegment2 = new LineSegment(crossPoint2.get(0), crossPoint2.get(1));
        Point center1 = lineSegment1.center();
        Point center2 = lineSegment2.center();

        double aDis1 = PointUtil.dis(lineSegment1.getStartPoint(), center1);
        double aDis2 = PointUtil.dis(lineSegment1.getEndPoint(), center1);

        double bDis1 = PointUtil.dis(lineSegment2.getStartPoint(), center2);
        double bDis2 = PointUtil.dis(lineSegment2.getEndPoint(), center2);

        double abs1 = Math.max(aDis1, bDis1) - Math.min(aDis1, bDis1);
        double v1 = (Math.min(aDis1, bDis1) - abs1 * 5) / Math.max(aDis1, bDis1);

        double abs2 = Math.max(aDis2, bDis2) - Math.min(aDis2, bDis2);
        double v2 = (Math.min(aDis2, bDis2) - abs2 * 5) / Math.max(aDis2, bDis2);

        if (v1 > 0.99D && v2 > 0.99D) {
            return Math.min(v1, v2);
        }
        if (v1 > 0.99D) {
            return v2;
        }
        if (v2 > 0.99D) {
            return v1;
        }

        return (v1 + v2) / 2;
    }

    public List<Point> getCrossPoint(LineSegment line) {

        List<Point> result = new ArrayList<>();
        for (LineSegment lineSegment : toLineSegment()) {
            Point crossPoint1;
            Point crossPoint = PointUtil.findIntersection(lineSegment, line);
            if (crossPoint != null && !result.contains(crossPoint)) {
                result.add(crossPoint);
            } else if ((crossPoint1 = PointUtil.getCrossPoint(lineSegment, line)) != null) {
                result.add(crossPoint1);
            } else if (line.onSegment(lineSegment.getStartPoint())) {
                result.add(lineSegment.getStartPoint());
            } else if (line.onSegment(lineSegment.getEndPoint())) {
                result.add(lineSegment.getEndPoint());
            }
        }
        return result;
    }

    public java.awt.Polygon toAwtPolygon() {
        return PointUtil.toAwtPolygon(this);
    }

    /**
     * 获取此多边形边界框, 边界框是平行于坐标空间的XY轴最小矩形, 可以完全包含多边形
     */
    public Rectangle2D.Double getBounding() {
        if (isEmpty()) {
            throw new IllegalArgumentException();
        }
        return new Rectangle2D.Double(getX(), getY(), getWidth(), getHeight());
    }

    /**
     * 判断此多边形是否包含点
     */
    public boolean contains(double x, double y) {
        throwEmpty();
        if (npoints <= 2 || !getBounding().contains(x, y)) {
            return false;
        }

        int hits = 0;
        double lastx = xpoints[npoints - 1];
        double lasty = ypoints[npoints - 1];
        double curx, cury;

        for (int i = 0; i < npoints; lastx = curx, lasty = cury, i++) {
            curx = xpoints[i];
            cury = ypoints[i];
            if (cury == lasty) {
                continue;
            }
            double leftX;
            if (curx < lastx) {
                if (x >= lastx) {
                    continue;
                }
                leftX = curx;
            } else {
                if (x >= curx) {
                    continue;
                }
                leftX = lastx;
            }

            double test1, test2;
            if (cury < lasty) {
                if (y < cury || y >= lasty) {
                    continue;
                }
                if (x < leftX) {
                    hits++;
                    continue;
                }
                test1 = x - curx;
                test2 = y - cury;
            } else {
                if (y < lasty || y >= cury) {
                    continue;
                }
                if (x < leftX) {
                    hits++;
                    continue;
                }
                test1 = x - lastx;
                test2 = y - lasty;
            }
            if (test1 < (test2 / (lasty - cury) * (lastx - curx))) {
                hits++;
            }
        }

        return ((hits & 1) != 0);
    }

    public boolean containsV2(double x, double y) {
        int i, j;
        for (i = 0, j = npoints - 1; i < npoints; j = i++) {
            if ((ypoints[i] <= y) && (y < ypoints[j]) &&
                    (x < (xpoints[j] - xpoints[i]) * (y - ypoints[i]) / (ypoints[j] - ypoints[i]) + xpoints[i])) {
                return false;
            }
        }
        return true;
    }

    public boolean containsV3(double x, double y) {
        boolean oddTransitions = false;
        for (int i = 0, j = npoints - 1; i < npoints; j = i++) {
            if ((ypoints[i] < y && ypoints[j] >= y) || (ypoints[j] < y && ypoints[i] >= y)) {
                if (xpoints[i] + (y - ypoints[i]) / (ypoints[j] - ypoints[i]) * (xpoints[j] - xpoints[i]) < x) {
                    oddTransitions = !oddTransitions;
                }
            }
        }
        return oddTransitions;
    }

    /**
     * 判断此多边形是否包含点
     */
    public boolean contains(Point p) {
        return contains(p.x, p.y);
    }

    /**
     * 是否为空
     */
    public boolean isEmpty() {
        return xpoints == null || ypoints == null || xpoints.length == 0 || ypoints.length == 0;
    }

    /**
     * 缩放变换
     */
    public void scaleTransform(Point centerPoint, double scale) {
        throwEmpty();
        if (centerPoint == null) {
            centerPoint = new Point(0, 0);
        }

        for (int i = 0; i < xpoints.length; i++) {
            xpoints[i] *= scale;
            ypoints[i] *= scale;
        }
        update();
    }

    /**
     * 高精度缩放
     */
    public void scaleTransformPre(Point centerPoint, double scale) {
        throwEmpty();
        if (centerPoint == null) {
            centerPoint = new Point(0, 0);
        }

        for (int i = 0; i < xpoints.length; i++) {
            xpoints[i] = ArithUtil.mul(xpoints[i], scale);
            ypoints[i] = ArithUtil.mul(ypoints[i], scale);
        }
        update();
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    /**
     * 顺时针旋转
     */
    public void rotateTransform(Point center, double angle) {
        throwEmpty();

        Polygon polygon = PointUtil.rotateTransform(this, angle, center);
        this.xpoints = polygon.xpoints;
        this.ypoints = polygon.ypoints;
        update();
    }

    /**
     * 返回此多边形的面积
     */
    public double getArea() {
        if (isEmpty()) {
            return 0;
        }

        return PointUtil.getArea(this);
    }

    /**
     * 判断另一个图形与此图形是否重叠
     */
    public boolean collide(Polygon polygon) {
        if (polygon == this || (this.xpoints == polygon.xpoints && this.ypoints == polygon.ypoints)) {
            return true;
        }

        for (int i = 0; i < polygon.npoints; i++) {
            if (this.contains(polygon.xpoints[i], polygon.ypoints[i])) {
                return true;
            }
        }
        for (int i = 0; i < this.xpoints.length; i++) {
            if (polygon.contains(this.xpoints[i], this.ypoints[i])) {
                return true;
            }
        }
        return false;
    }

    /**
     * 更新坐标信息
     */
    public void update() {
        throwEmpty();
        this.x = null;
        this.y = null;
        this.maxX = null;
        this.maxY = null;
        this.width = null;
        this.height = null;

        getWidth();
        getHeight();
    }


    /**
     * 移动此图形
     */
    public void move(Point dst) {
        move(dst.x, dst.y);
    }

    /**
     * 移动
     */
    public void move(double x, double y) {
        if (isEmpty()) {
            throw new IllegalArgumentException();
        }
        translate(PointUtil.getTranslateVector(getX(), getY(), x, y));
    }

    /**
     * 平移
     *
     * @param vector 移动向量
     */
    public void translate(Vector vector) {
        translate(vector.getX(), vector.getY());
    }

    /**
     * 平移
     */
    public void translate(double xn, double yn) {
        if (xn == 0.0D && yn == 0.0D) {
            return;
        }

        throwEmpty();
        for (int i = 0; i < this.xpoints.length; i++) {
            this.xpoints[i] += xn;
            this.ypoints[i] += yn;
        }
        if (this.x != null) {
            this.x += xn;
        }
        if (this.y != null) {
            this.y += yn;
        }
        if (this.maxX != null) {
            this.maxX += xn;
        }
        if (this.maxY != null) {
            this.maxY += yn;
        }
    }

    /**
     * Returns an iterator object that iterates along the boundary of this
     * <code>Polygon</code> and provides access to the geometry
     * of the outline of this <code>Polygon</code>.  An optional
     * {@link AffineTransform} can be specified so that the coordinates
     * returned in the iteration are transformed accordingly.
     *
     * @param at an optional <code>AffineTransform</code> to be applied to the
     *           coordinates as they are returned in the iteration, or
     *           <code>null</code> if untransformed coordinates are desired
     * @return a {@link PathIterator} object that provides access to the
     * geometry of this <code>Polygon</code>.
     * @since 1.2
     */
    public PathIterator getPathIterator(AffineTransform at) {
        return new PolygonPathIterator(this, at);
    }

    public double getCenterX() {
        return ArithUtil.add(getX(), ArithUtil.div(getWidth(), 2));
    }

    public double getCenterY() {
        return ArithUtil.add(getY(), ArithUtil.div(getHeight(), 2));
    }

    public Point getCenter() {
        return new Point(getCenterX(), getCenterY());
    }

    public List<Point> toPointList() {
        List<Point> points = new LinkedList<>();
        for (int i = 0; i < xpoints.length; i++) {
            points.add(new Point(xpoints[i], ypoints[i]));
        }
        return points;
    }

    public Point[] toPointArray() {
        Point[] points = new Point[xpoints.length];
        for (int i = 0; i < xpoints.length; i++) {
            points[i] = new Point(xpoints[i], ypoints[i]);
        }
        return points;
    }

    public double[] getXpoints() {
        return xpoints;
    }

    @Deprecated
    public void setXpoints(double[] xpoints) {
        this.xpoints = xpoints;
    }

    public double[] getYpoints() {
        return ypoints;
    }

    @Deprecated
    public void setYpoints(double[] ypoints) {
        this.ypoints = ypoints;
    }

    public int getNpoints() {
        return npoints;
    }

    @Deprecated
    public void setNpoints(int npoints) {
        this.npoints = npoints;
    }

    public double getX() {
        throwEmpty();
        if (x == null) {
            x = Arrays.stream(xpoints).min().orElse(0.0D);
        }
        return x;
    }

    public double getMaxX() {
        throwEmpty();
        if (maxX == null) {
            maxX = Arrays.stream(xpoints).max().orElse(0.0D);
        }
        return maxX;
    }

    public double getY() {
        throwEmpty();
        if (y == null) {
            y = Arrays.stream(ypoints).min().orElse(0.0D);
        }
        return y;
    }

    public double getMaxY() {
        throwEmpty();
        if (maxY == null) {
            maxY = Arrays.stream(ypoints).max().orElse(0.0D);
        }
        return maxY;
    }

    public double getWidth() {
        if (width == null) {
            width = getMaxX() - getX();
        }
        return width;
    }

    public double getHeight() {
        if (height == null) {
            height = getMaxY() - getY();
        }
        return height;
    }

    private void throwEmpty() {
        if (isEmpty()) {
            throw new IllegalArgumentException("Polygon.isEmpty() = true");
        }
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

    @Override
    public String toString() {
        return "Polygon{" +
                "id='" + id + '\'' +
                ", xpoints=" + Arrays.toString(xpoints) +
                ", ypoints=" + Arrays.toString(ypoints) +
                ", x=" + x +
                ", y=" + y +
                ", width=" + width +
                ", height=" + height +
                ", npoints=" + npoints +
                '}';
    }

    @Override
    public Polygon clone() {
        try {
            Polygon pog = (Polygon) super.clone();
            pog.xpoints = new double[this.xpoints.length];
            pog.ypoints = new double[this.ypoints.length];

            System.arraycopy(this.xpoints, 0, pog.xpoints, 0, this.xpoints.length);
            System.arraycopy(this.ypoints, 0, pog.ypoints, 0, this.ypoints.length);

            pog.id = this.id;
            pog.bId = this.bId;
            pog.npoints = this.npoints;
            pog.x = null;
            pog.y = null;
            pog.maxX = null;
            pog.maxY = null;
            pog.width = null;
            pog.height = null;
            return pog;
        } catch (CloneNotSupportedException e) {
            throw new RuntimeException(e);
        }
    }

    static class PolygonPathIterator implements PathIterator {
        Polygon poly;
        AffineTransform transform;
        int index;

        public PolygonPathIterator(Polygon pg, AffineTransform at) {
            poly = pg;
            transform = at;
            if (pg.npoints == 0) {
                // Prevent a spurious SEG_CLOSE segment
                index = 1;
            }
        }

        /**
         * Returns the winding rule for determining the interior of the
         * path.
         *
         * @return an integer representing the current winding rule.
         * @see PathIterator#WIND_NON_ZERO
         */
        public int getWindingRule() {
            return WIND_EVEN_ODD;
        }

        /**
         * Tests if there are more points to read.
         *
         * @return <code>true</code> if there are more points to read;
         * <code>false</code> otherwise.
         */
        public boolean isDone() {
            return index > poly.npoints;
        }

        /**
         * Moves the iterator forwards, along the primary direction of
         * traversal, to the next segment of the path when there are
         * more points in that direction.
         */
        public void next() {
            index++;
        }

        /**
         * Returns the coordinates and type of the current path segment in
         * the iteration.
         * The return value is the path segment type:
         * SEG_MOVETO, SEG_LINETO, or SEG_CLOSE.
         * A <code>float</code> array of length 2 must be passed in and
         * can be used to store the coordinates of the point(s).
         * Each point is stored as a pair of <code>float</code> x,&nbsp;y
         * coordinates.  SEG_MOVETO and SEG_LINETO types return one
         * point, and SEG_CLOSE does not return any points.
         *
         * @param coords a <code>float</code> array that specifies the
         *               coordinates of the point(s)
         * @return an integer representing the type and coordinates of the
         * current path segment.
         * @see PathIterator#SEG_MOVETO
         * @see PathIterator#SEG_LINETO
         * @see PathIterator#SEG_CLOSE
         */
        public int currentSegment(float[] coords) {
            if (index >= poly.npoints) {
                return SEG_CLOSE;
            }
            coords[0] = (float) poly.xpoints[index];
            coords[1] = (float) poly.ypoints[index];
            if (transform != null) {
                transform.transform(coords, 0, coords, 0, 1);
            }
            return (index == 0 ? SEG_MOVETO : SEG_LINETO);
        }

        /**
         * Returns the coordinates and type of the current path segment in
         * the iteration.
         * The return value is the path segment type:
         * SEG_MOVETO, SEG_LINETO, or SEG_CLOSE.
         * A <code>double</code> array of length 2 must be passed in and
         * can be used to store the coordinates of the point(s).
         * Each point is stored as a pair of <code>double</code> x,&nbsp;y
         * coordinates.
         * SEG_MOVETO and SEG_LINETO types return one point,
         * and SEG_CLOSE does not return any points.
         *
         * @param coords a <code>double</code> array that specifies the
         *               coordinates of the point(s)
         * @return an integer representing the type and coordinates of the
         * current path segment.
         * @see PathIterator#SEG_MOVETO
         * @see PathIterator#SEG_LINETO
         * @see PathIterator#SEG_CLOSE
         */
        public int currentSegment(double[] coords) {
            if (index >= poly.npoints) {
                return SEG_CLOSE;
            }
            coords[0] = poly.xpoints[index];
            coords[1] = poly.ypoints[index];
            if (transform != null) {
                transform.transform(coords, 0, coords, 0, 1);
            }
            return (index == 0 ? SEG_MOVETO : SEG_LINETO);
        }
    }
}
